/*
 * Copyright(c) 2012 Donghong Inc.
 */
package com.hatic.login;


import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.jxstar.dao.DaoParam;
import org.jxstar.service.BusinessObject;

import com.chinasofti.portlet.service.client.BusinessOrder;
import com.chinasofti.portlet.service.client.BusinessOrderHttpServiceLocator;

/**
 * 取到当前新增的审批分配消息，发送到接口中。
 * 1、新建一张表：pm_assign，字段：assign_id, send_date；
 * 2、这些记录需要构建xml发送到接口中新增：select * from wf_assign where assign_id not in (select assign_id from pm_assign)
 * 3、这些记录需要构建xml发送到接口中删除：select * from pm_assign where assign_id not in (select assign_id from wf_assign)
 * 4、注意：构建“待办人UserID”时，根据assign_userid与用户映射表，找到cas_user_id.
 * 5、注意: 传递的URL类似：http://localhost:8080/pm/cas_main.jsp?assign_id=jxstar67716431
 * 5、定义一个定时任务，每5分钟执行一次。
 * 
 * @author TonyTan
 * @version 1.0, 2012-7-18
 */
public class PmAssignBO extends BusinessObject {

	public String send() {
		String reqXml = "";
		StringBuffer headXml=new StringBuffer();
		String dataXml = "";
		StringBuffer endXml=new StringBuffer();
		
		
		String action = "";
		String pending_pk = "";
		String pendingCode = "";
		String pendingPersonID = "";
		String pendingTitle = "";
		String pendingDate = "";
		String pmURL = "http://10.65.128.107:9084/pm/cas_index.jsp?assign_id=";
		String pandingType = "中烟项目管理系统";
		String pandingCityCode ="";
		String notes ="pms";
		String userName = "";
		String timeNow=date2str(new Date(),"yyyy-MM-dd HH:mm:ss");
		String misId=date2str(new Date(),"yyyyMMddHHmmss");
		List<Map<String,String>> lsadd = queryAssignAdd();
		List<Map<String,String>> lsdel = queryAssignDel();
		if(lsadd.size() == 0 && lsdel.size() == 0){
			_log.showDebug("待办任务没有变化，不需要更新！");
			return _returnFaild;							
		}else{
			//新增 插入记录
			headXml.append("<?xml version=\"1.0\" encoding=\"GBK\"?>");
			headXml.append("<dataset>");
			headXml.append("<head>");
			headXml.append("<msg_id>PM_PENDING_"+misId+"</msg_id>");
			headXml.append("<ws_mark>HNZY_ESB_Services</ws_mark>");
			headXml.append("<ws_method>transPendingOrder</ws_method>");
			headXml.append(" <ws_param>xml</ws_param>");
			headXml.append("<curr_time>"+timeNow+"</curr_time>");
			headXml.append("<curr_user>icss</curr_user>"); 			    
			headXml.append("</head>");
			headXml.append("<datalist>");
			endXml.append("</datalist>");
			endXml.append("</dataset>");
			if(lsadd.size() > 0){
				for(int i = 0 ; i < lsadd.size() ; i++ ){
					action = "INSERT";
					Map<String,String> mp = lsadd.get(i);
					pending_pk = mp.get("assign_id");
					String assign_userid = mp.get("assign_userid");//pm系统用户ID
					Map<String,String> mpCasUser = PmLoginUtil.queryCasUser(assign_userid);
					
					pendingCode = "";
					
					pendingPersonID = mpCasUser.get("cas_user_id");
					userName = mpCasUser.get("cas_user_name");
					
					pendingTitle = mp.get("task_desc");
					pendingDate = mp.get("start_date");
					
					String pendingURL = pmURL + pending_pk;
				
					String sb = addBuffer(action,pending_pk,pendingCode,pendingPersonID,pendingTitle, 
							pendingDate, pendingURL,"0",pandingType, pandingCityCode,notes,userName);
					
					dataXml =dataXml +sb ;
				}
			}
			//新增 删除记录
			if(lsdel.size() > 0){
				for(int i = 0 ; i < lsdel.size() ; i++ ){
					action = "DELETE";
					Map<String,String> mp = lsdel.get(i);
					pending_pk = mp.get("assign_id");
					String sql = "SELECT * FROM wf_assign where assign_id = ?";
					DaoParam param = _dao.createParam(sql);
					param.addStringValue(pending_pk);
					Map<String,String> mpAssign = _dao.queryMap(param);
					
					String assign_userid = mpAssign.get("assign_userid");//pm系统用户ID
					Map<String,String> mpCasUser = PmLoginUtil.queryCasUser(assign_userid);
					
					pendingCode = "";
					
					pendingPersonID = mpCasUser.get("cas_user_id");
					userName = mpCasUser.get("cas_user_name");
					
					pendingTitle = mp.get("task_desc");
					pendingDate = mp.get("start_date");
					
					String pendingURL = pmURL + pending_pk;
				
					String sb = addBuffer(action,pending_pk,pendingCode,pendingPersonID,pendingTitle, 
							pendingDate, pendingURL,"2", pandingType, pandingCityCode,notes,userName);
					
					dataXml =dataXml +sb ;
					
				}
			}
		}
			
		
		reqXml=headXml+dataXml+endXml;
		//_log.showDebug(reqXml);
		
		try {
			BusinessOrder order = new BusinessOrderHttpServiceLocator().getBusinessOrderHttpPort();
			
			String result = order.transServices(reqXml);
			_log.showDebug("集中平台代办返回结果："+result);
			if(result.indexOf("调用成功")>0){
				if(lsadd.size() > 0){
					for(int i = 0; i < lsadd.size() ; i++ ){
						Map<String,String> mp = lsadd.get(i);
						insertPmAssign(mp.get("assign_id"));
					}
				}
				if(lsdel.size() > 0){
					for(int i = 0 ; i < lsdel.size() ; i++ ){
						Map<String,String> mp = lsdel.get(i);
						delPmAssign(mp.get("assign_id"));
					}
				}
			}
				
		} 
		catch (Exception e) {
			e.printStackTrace();
		}  
		
		return _returnSuccess;
	}
	
	//构建xml信息
	public String addBuffer(String action,String pending_pk,String pendingCode,String pendingPersonID,String pendingTitle,
			String pendingDate,String pendingURL,String pandingStatus,String pandingType,String pandingCityCode,String notes,String userName){
		StringBuffer sb = new StringBuffer();
		sb.append("<data>");
		sb.append("<action>"+action+"</action>");
		sb.append("<pending_pk>"+pending_pk+"</pending_pk>");
		sb.append("<pendingCode>"+pendingCode+"</pendingCode>");
		sb.append("<pendingPersonID>"+pendingPersonID+"</pendingPersonID>");
		sb.append("<pendingTitle><![CDATA[ "+pendingTitle+" ]]></pendingTitle>");
		sb.append("<pendingDate>"+pendingDate+"</pendingDate>");
		sb.append("<pendingURL><![CDATA[ "+pendingURL+" ]]></pendingURL>");
		sb.append("<pandingStatus>"+pandingStatus+"</pandingStatus>");
		sb.append("<pandingType><![CDATA[ "+pandingType+" ]]></pandingType>");
		sb.append("<pandingCityCode>"+pandingCityCode+"</pandingCityCode>");
		sb.append("<notes>"+notes+"</notes >");
		sb.append("<pendingPri>1</pendingPri>");
		sb.append("<userName><![CDATA[ "+userName+" ]]></userName>");
		sb.append("<sms_status>0</sms_status>");
		sb.append("</data>");
			
		return sb.toString();
	}
	
	//查找新的任务信息，需要构建新审批任务xml信息的记录
	List<Map<String,String>> queryAssignAdd(){
		String sql = "select * from wf_assign where assign_id not in (select assign_id from pm_assign) ";
		DaoParam param = _dao.createParam(sql);
		return _dao.query(param);
	}
	//查找新的任务信息，需要构建删除已审批任务xml信息的记录
	List<Map<String,String>> queryAssignDel(){
		String sql = "select * from pm_assign where assign_id not in (select assign_id from wf_assign)";
		DaoParam param = _dao.createParam(sql);
		return _dao.query(param);
	}
	private boolean insertPmAssign(String pmId){
		String sql= "insert into pm_assign (assign_id,send_date) (select assign_id,Sysdate from wf_assign where assign_id =?) ";
		DaoParam param = _dao.createParam(sql);
		param.addStringValue(pmId);
		return _dao.update(param);
	}
	private boolean delPmAssign(String pmId){
		String sql= "delete from pm_assign where assign_id =? ";
		DaoParam param = _dao.createParam(sql);
		param.addStringValue(pmId);
		return _dao.update(param);
	}
	
	public static String date2str(Date date,String pattern){
		DateFormat df=new SimpleDateFormat(pattern);
		String str=df.format(date);
		return str;
		}
	
}
